package servlet;

import service.ArticleService;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/deleteArticle")
public class DeleteArticleServlet extends HttpServlet {
    private ArticleService articleService = new ArticleService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 检查登录状态
        Integer userId = SessionUtils.getCurrentUserId(request);
        if (userId == null) {
            response.sendRedirect("login.html");
            return;
        }

        try {
            // 获取文章ID
            String articleIdStr = request.getParameter("id");
            if (articleIdStr == null || articleIdStr.trim().isEmpty()) {
                request.getSession().setAttribute("error", "文章ID不能为空");
                response.sendRedirect("articleList");
                return;
            }

            int articleId = Integer.parseInt(articleIdStr);
            
            // 执行删除操作
            boolean success = articleService.deleteArticle(articleId, userId);
            
            if (success) {
                request.getSession().setAttribute("success", "文章删除成功");
            } else {
                request.getSession().setAttribute("error", "文章删除失败，可能没有权限或文章不存在");
            }
            
            // 重定向到文章列表
            response.sendRedirect("articleList");
        } catch (NumberFormatException e) {
            request.getSession().setAttribute("error", "无效的文章ID");
            response.sendRedirect("articleList");
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("error", "系统错误，请稍后重试");
            response.sendRedirect("articleList");
        }
    }
}